// 运行数据管理相关的JavaScript代码
const OPERATION_API_BASE = '/api/feibiao/operation';

// 加载运行数据列表
function loadOperationList(page = 0, size = 10, sort = 'operationId,asc') {
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 保存当前排序方式到 localStorage
    if (sort) {
        localStorage.setItem('operationSort', sort);
    } else {
        const savedSort = localStorage.getItem('operationSort');
        if (savedSort) {
            sort = savedSort;
        }
    }
    
    console.log(`尝试加载运行数据: ${OPERATION_API_BASE}?page=${page}&size=${size}&sort=${sort}`);
    
    fetch(`${OPERATION_API_BASE}?page=${page}&size=${size}&sort=${sort}`)
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => {
                    console.error('API请求失败:', response.status, response.statusText, text);
                    try {
                        const error = JSON.parse(text);
                        throw new Error(`服务器错误 (${response.status}): ${error.message || error.error || response.statusText}`);
                    } catch (e) {
                        if (e instanceof SyntaxError) {
                            throw new Error(`服务器错误 (${response.status}): ${text || response.statusText}`);
                        }
                        throw e;
                    }
                });
            }
            return response.json();
        })
        .then(data => {
            console.log('成功获取运行数据:', data);
            renderOperationTable(data, sort);
        })
        .catch(error => {
            console.error('获取运行数据失败:', error);
            mainContent.innerHTML = `
                <div class="error-container">
                    <h2>加载数据失败</h2>
                    <p>错误信息: ${error.message}</p>
                    <div class="error-actions">
                        <button class="btn btn-primary" onclick="loadOperationList()">重试</button>
                    </div>
                </div>
            `;
            showMessage('获取运行数据失败: ' + error.message, 'error');
        });
}

// 渲染运行数据表格
function renderOperationTable(data, sort = 'operationId,asc') {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机运行数据管理</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showOperationForm()"><i class="fa fa-plus"></i> 新增</button>
            </div>
        </div>
        <div class="content-toolbar">
            <div class="search-box">
                <input type="text" class="search-input" id="operationSearchInput" placeholder="输入电机ID搜索...">
                <button class="search-btn" onclick="searchOperation()">搜索</button>
            </div>
            <div class="sort-container">
                <label for="sortSelect">排序方式:</label>
                <select id="sortSelect" onchange="changeSorting()">
                    <option value="operationId,asc">ID升序</option>
                    <option value="operationId,desc">ID降序</option>
                    <option value="operationTime,desc">运行时间降序（新→旧）</option>
                    <option value="operationTime,asc">运行时间升序（旧→新）</option>
                    <option value="motorId,asc">电机ID升序</option>
                    <option value="motorId,desc">电机ID降序</option>
                </select>
            </div>
        </div>
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>电机ID</th>
                        <th>运行时间</th>
                        <th>电流(A)</th>
                        <th>电压(V)</th>
                        <th>温度(℃)</th>
                        <th>转速(rpm)</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
    `;

    if (data.content && data.content.length > 0) {
        data.content.forEach(operation => {
            html += `
                <tr>
                    <td>${operation.operationId}</td>
                    <td>${operation.motorId}</td>
                    <td>${formatDateTime(operation.operationTime)}</td>
                    <td>${operation.current || '-'}</td>
                    <td>${operation.voltage || '-'}</td>
                    <td>${operation.temperature || '-'}</td>
                    <td>${operation.rotationSpeed || '-'}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewOperation(${operation.operationId})">查看</a>
                        <a href="javascript:void(0)" onclick="editOperation(${operation.operationId})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteOperation(${operation.operationId})">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += `
            <tr>
                <td colspan="8" class="text-center">暂无数据</td>
            </tr>
        `;
    }

    html += `
                </tbody>
            </table>
        </div>
    `;

    // 添加分页控件
    if (data.totalPages > 1) {
        html += `
            <div class="pagination">
                <button class="page-btn" onclick="loadOperationList(${Math.max(0, data.number - 1)}, ${data.size}, '${sort}')" ${data.first ? 'disabled' : ''}>&laquo; 上一页</button>
                <span class="page-info">第 ${data.number + 1} 页，共 ${data.totalPages} 页</span>
                <button class="page-btn" onclick="loadOperationList(${Math.min(data.totalPages - 1, data.number + 1)}, ${data.size}, '${sort}')" ${data.last ? 'disabled' : ''}>下一页 &raquo;</button>
            </div>
        `;
    }

    mainContent.innerHTML = html;
    
    // 设置排序下拉框的值
    if (document.getElementById('sortSelect')) {
        document.getElementById('sortSelect').value = sort;
    }
}

// 显示运行数据表单
function showOperationForm(operation = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = operation !== null;
    
    let html = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}运行数据</h2>
        </div>
        <div class="form-container">
            <form id="operationForm" onsubmit="return submitOperationForm(event)">
                ${isEdit ? `<input type="hidden" id="operationId" value="${operation.operationId}">` : ''}
                <div class="form-group">
                    <label for="motorId">电机ID:</label>
                    <input type="text" id="motorId" name="motorId" class="form-control" required
                           value="${isEdit ? operation.motorId : ''}">
                </div>
                <div class="form-group">
                    <label for="operationTime">运行时间:</label>
                    <input type="datetime-local" id="operationTime" name="operationTime" class="form-control" required
                           value="${isEdit ? formatDateTimeForInput(operation.operationTime) : ''}">
                </div>
                <div class="form-group">
                    <label for="current">电流(A):</label>
                    <input type="number" id="current" name="current" class="form-control" step="0.01"
                           value="${isEdit ? operation.current : ''}">
                </div>
                <div class="form-group">
                    <label for="voltage">电压(V):</label>
                    <input type="number" id="voltage" name="voltage" class="form-control" step="0.01"
                           value="${isEdit ? operation.voltage : ''}">
                </div>
                <div class="form-group">
                    <label for="temperature">温度(℃):</label>
                    <input type="number" id="temperature" name="temperature" class="form-control" step="0.01"
                           value="${isEdit ? operation.temperature : ''}">
                </div>
                <div class="form-group">
                    <label for="rotationSpeed">转速(rpm):</label>
                    <input type="number" id="rotationSpeed" name="rotationSpeed" class="form-control" step="0.01"
                           value="${isEdit ? operation.rotationSpeed : ''}">
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">${isEdit ? '更新' : '保存'}</button>
                    <button type="button" class="btn btn-default" onclick="loadOperationList()">取消</button>
                </div>
            </form>
        </div>
    `;
    
    mainContent.innerHTML = html;
}

// 查看运行数据详情
function viewOperation(id) {
    fetch(`${OPERATION_API_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(operation => {
            showOperationDetail(operation);
        })
        .catch(error => {
            console.error('获取运行数据详情失败:', error);
            showMessage('获取运行数据详情失败: ' + error.message, 'error');
        });
}

// 显示运行数据详情
function showOperationDetail(operation) {
    const mainContent = document.getElementById('mainContent');
    
    let html = `
        <div class="content-header">
            <h2 class="content-title">运行数据详情</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadOperationList()"><i class="fa fa-arrow-left"></i> 返回列表</button>
            </div>
        </div>
        
        <div class="detail-container">
            <div class="detail-card">
                <div class="detail-card-header">
                    <h3><i class="fa fa-info-circle"></i> 基本信息</h3>
                </div>
                <div class="detail-card-body">
                    <div class="detail-info-grid">
                        <div class="detail-group">
                            <label>ID</label>
                            <div class="detail-value">${operation.operationId || '--'}</div>
                        </div>
                        
                        <div class="detail-group">
                            <label>电机ID</label>
                            <div class="detail-value">${operation.motorId || '--'}</div>
                        </div>
                        
                        <div class="detail-group">
                            <label>运行时间</label>
                            <div class="detail-value">${formatDateTime(operation.operationTime) || '--'}</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="detail-card">
                <div class="detail-card-header">
                    <h3><i class="fa fa-tachometer"></i> 运行参数</h3>
                </div>
                <div class="detail-card-body">
                    <div class="detail-info-grid">
                        <div class="detail-group">
                            <label>电流(A)</label>
                            <div class="detail-value">${operation.current || '--'}</div>
                        </div>
                        
                        <div class="detail-group">
                            <label>电压(V)</label>
                            <div class="detail-value">${operation.voltage || '--'}</div>
                        </div>
                        
                        <div class="detail-group">
                            <label>温度(℃)</label>
                            <div class="detail-value">${operation.temperature || '--'}</div>
                        </div>
                        
                        <div class="detail-group">
                            <label>转速(rpm)</label>
                            <div class="detail-value">${operation.rotationSpeed || '--'}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="detail-actions">
            <button class="btn btn-primary" onclick="editOperation(${operation.operationId})"><i class="fa fa-edit"></i> 编辑</button>
            <button class="btn btn-danger" onclick="deleteOperation(${operation.operationId})"><i class="fa fa-trash"></i> 删除</button>
            <button class="btn btn-default" onclick="loadOperationList()"><i class="fa fa-list"></i> 返回列表</button>
        </div>
    `;
    
    mainContent.innerHTML = html;
}

// 提交运行数据表单
function submitOperationForm(event) {
    event.preventDefault();
    
    // 获取表单数据
    const motorId = document.getElementById('motorId').value.trim();
    const operationTime = document.getElementById('operationTime').value;
    const current = document.getElementById('current').value;
    const voltage = document.getElementById('voltage').value;
    const temperature = document.getElementById('temperature').value;
    const rotationSpeed = document.getElementById('rotationSpeed').value;
    
    // 数据验证
    if (!motorId) {
        showMessage('请输入电机ID', 'error');
        return false;
    }
    
    if (!operationTime) {
        showMessage('请选择运行时间', 'error');
        return false;
    }
    
    // 验证数值范围
    const validateNumber = (value, fieldName, min, max) => {
        if (value && (isNaN(value) || value < min || value > max)) {
            showMessage(`${fieldName}必须在${min}到${max}之间`, 'error');
            return false;
        }
        return true;
    };
    
    if (!validateNumber(current, '电流', -1000, 1000)) return false;
    if (!validateNumber(voltage, '电压', 0, 1000)) return false;
    if (!validateNumber(temperature, '温度', -50, 200)) return false;
    if (!validateNumber(rotationSpeed, '转速', 0, 10000)) return false;
    
    const formData = {
        motorId: motorId,
        operationTime: operationTime,
        current: current ? parseFloat(current) : null,
        voltage: voltage ? parseFloat(voltage) : null,
        temperature: temperature ? parseFloat(temperature) : null,
        rotationSpeed: rotationSpeed ? parseFloat(rotationSpeed) : null
    };
    
    const operationId = document.getElementById('operationId');
    const isEdit = operationId !== null;
    const url = isEdit ? `${OPERATION_API_BASE}/${operationId.value}` : OPERATION_API_BASE;
    const method = isEdit ? 'PUT' : 'POST';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(`服务器错误 (${response.status}): ${text || response.statusText}`);
            });
        }
        return response.json();
    })
    .then(data => {
        showMessage(`${isEdit ? '更新' : '新增'}运行数据成功`, 'success');
        loadOperationList();
    })
    .catch(error => {
        console.error(`${isEdit ? '更新' : '新增'}运行数据失败:`, error);
        showMessage(`${isEdit ? '更新' : '新增'}运行数据失败: ` + error.message, 'error');
    });
    
    return false;
}

// 编辑运行数据
function editOperation(id) {
    fetch(`${OPERATION_API_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(operation => {
            showOperationForm(operation);
        })
        .catch(error => {
            console.error('获取运行数据详情失败:', error);
            showMessage('获取运行数据详情失败: ' + error.message, 'error');
        });
}

// 删除运行数据
function deleteOperation(id) {
    if (confirm('确定要删除这条运行数据吗？')) {
        fetch(`${OPERATION_API_BASE}/${id}`, {
            method: 'DELETE'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            showMessage('删除运行数据成功', 'success');
            loadOperationList();
        })
        .catch(error => {
            console.error('删除运行数据失败:', error);
            showMessage('删除运行数据失败: ' + error.message, 'error');
        });
    }
}

// 搜索运行数据
function searchOperation() {
    const keyword = document.getElementById('operationSearchInput').value.trim();
    if (!keyword) {
        loadOperationList();
        return;
    }
    
    const currentSort = document.getElementById('sortSelect').value || localStorage.getItem('operationSort') || 'operationId,asc';
    
    fetch(`${OPERATION_API_BASE}/by-motor?motorId=${encodeURIComponent(keyword)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            const pageData = {
                content: data,
                totalPages: 1,
                number: 0,
                size: data.length,
                first: true,
                last: true
            };
            renderOperationTable(pageData, currentSort);
        })
        .catch(error => {
            console.error('搜索运行数据失败:', error);
            showMessage('搜索运行数据失败: ' + error.message, 'error');
        });
}

// 更改排序方式
function changeSorting() {
    const sortValue = document.getElementById('sortSelect').value;
    loadOperationList(0, 10, sortValue);
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '-';
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 格式化日期时间为input datetime-local的值
function formatDateTimeForInput(dateTimeStr) {
    if (!dateTimeStr) return '';
    const date = new Date(dateTimeStr);
    return date.toISOString().slice(0, 16);
}

// 将函数暴露给全局
if (typeof window !== 'undefined') {
    window.loadOperationList = loadOperationList;
    window.renderOperationTable = renderOperationTable;
    window.showOperationForm = showOperationForm;
    window.viewOperation = viewOperation;
    window.showOperationDetail = showOperationDetail;
    window.submitOperationForm = submitOperationForm;
    window.editOperation = editOperation;
    window.deleteOperation = deleteOperation;
    window.searchOperation = searchOperation;
    window.changeSorting = changeSorting;
    
    console.log('电机运行数据管理模块加载完成');
} 